<template>
  <view>
    <canvas @touchstart="onTouchstart" class="canvas" canvas-id="canvas"></canvas>
    <button @click="drawText">drawText</button>
    <button @click="getImageData(true)">getImageData</button>
    <button @click="measureText(false)">measureText</button>
    <button @click="measureText(true)">measureText async</button>
  </view>
</template>

<script>
import { pathToBase64 } from 'image-tools'

export default {
  data () {
    return {}
  },
  onLoad () {

  },
  onReady () {

  },
  methods: {
    drawText () {
      const context = uni.createCanvasContext('canvas', this)
      context.clearRect(0, 0, 300, 300)
      // 小程序真机不支持自定义字体
      context.font = '10px square'
      // 对齐测试
      context.fillText('\ue5de', 0, 10)
      context.setTextAlign('center')
      context.fillText('\ue5de', 150, 10)
      context.setTextAlign('right')
      context.fillText('\ue5de', 300, 10)
      context.setTextAlign('left')
      // 位置测试
      context.setFontSize(20)
      context.fillText('\ue5de', 0, 30)
      context.fillText('\ue5de', 100, 30)
      // 大小测试
      context.setFontSize(40)
      context.fillText('\ue5de', 0, 100)
      context.draw()
    },
    async getImageData (log) {
      const res = await new Promise((resolve, reject) => {
        uni.canvasToTempFilePath({
          destWidth: 300,
          destHeight: 300,
          canvasId: 'canvas',
          success: resolve,
          fail: reject
        })
      })
      const { tempFilePath } = res
      if (log) {
        console.log('tempFilePath:', tempFilePath)
      }
      const base64 = pathToBase64(tempFilePath)
      return await base64
    },
    async measureText (async) {
      const text = '\ue5de'
      const context = uni.createCanvasContext('canvas', this)
      // 小程序不支持测量自定义字体
      context.font = '10px square'
      const start = Date.now()
      if (async) {
        return new Promise((resolve, reject) => {
          context.measureText(text, (textMetrics) => {
            console.log('measureText end:', textMetrics, Date.now() - start)
            resolve(textMetrics)
          })
        })
      }
      const textMetrics = context.measureText(text)
      console.log('textMetrics end:', textMetrics, Date.now() - start)
      return textMetrics
    },
    onTouchstart (event) {
      console.log(event)
    }
  }
}
</script>

<style>
@font-face {
  font-family: "square";
  src: url("/static/square.ttf");
}
page {
  font-family: "square";
}
canvas {
  width: 300px;
  height: 300px;
  background-color: aqua;
  margin-top: 10px;
  margin-left: 10px;
}
</style>
